package cn.edu.bjfu.practice.practice.student.service.impl;

import cn.edu.bjfu.practice.practice.manager.dao.TeacherDao;
import cn.edu.bjfu.practice.practice.manager.pojo.domain.UserTable;
import cn.edu.bjfu.practice.practice.student.dao.AttachmentDao;
import cn.edu.bjfu.practice.practice.student.dao.TaskDao;
import cn.edu.bjfu.practice.practice.student.pojo.domain.Attachment;
import cn.edu.bjfu.practice.practice.student.pojo.domain.Task;
import cn.edu.bjfu.practice.practice.student.pojo.query.AddTaskForm;
import cn.edu.bjfu.practice.practice.student.pojo.query.ChangeProForm;
import cn.edu.bjfu.practice.practice.student.pojo.query.ModifyTaskForm;
import cn.edu.bjfu.practice.practice.student.pojo.query.RemoveMemberForm;
import cn.edu.bjfu.practice.practice.student.pojo.vo.TaskDetailView;
import cn.edu.bjfu.practice.practice.student.pojo.vo.TaskView;
import cn.edu.bjfu.practice.practice.student.service.ProjectService;
import cn.edu.bjfu.practice.practice.teacher.dao.DocumentDao;
import cn.edu.bjfu.practice.practice.teacher.dao.ProjectDao;
import cn.edu.bjfu.practice.practice.teacher.dao.StudentGroupDao;
import cn.edu.bjfu.practice.practice.teacher.dao.TeamDao;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.Project;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.Resource;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.StudentGroup;
import cn.edu.bjfu.practice.practice.teacher.pojo.domain.Team;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.CaseView;
import cn.edu.bjfu.practice.practice.teacher.pojo.vo.ProjectTeamView;
import cn.edu.bjfu.practice.practice.teacher.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    TeamDao teamDao;

    @Autowired
    TaskDao taskDao;

    @Autowired
    StudentGroupDao studentGroupDao;

    @Autowired
    AttachmentDao attachmentDao;

    @Autowired
    DocumentDao documentDao;

    @Autowired
    ProjectDao projectDao;

    @Value("${task.basePath}")
    String taskPath;

    @Override
    public List<ProjectTeamView> selectTeam() {
        return teamDao.selectTeam(-1);
    }

    @Override
    public int joinTeam(Integer id, Integer user_id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("sno", user_id);
        map.put("deleted", false);
        if(studentGroupDao.selectByMap(map).size() == 0) {
            //删除所有该学生与该组的关系记录
            HashMap<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("sno", user_id);
            deleteMap.put("group_id", id);
            studentGroupDao.deleteByMap(deleteMap);

            //学生重新加入该组
            StudentGroup studentGroup = new StudentGroup();
            studentGroup.setSno(user_id);
            studentGroup.setGroup_id(id);
            studentGroupDao.insert(studentGroup);
            return 1;
        }else
            return 0;
    }

    @Override
    public int removeMember(RemoveMemberForm form) {
        Team team = teamDao.getTeamById(form.getTeam_id());
        if(team.getLeader_id().equals(form.getLeader_id()) && !team.getLeader_id().equals(form.getMember_id())) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("sno", form.getMember_id());
            map.put("group_id", form.getTeam_id());
            studentGroupDao.deleteByMap(map);
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public List<String> addTask(AddTaskForm form) {
        Task task = new Task();
        task.setName(form.getName());
        task.setIntroduce(form.getIntroduce());
        task.setStage(form.getStage());
        task.setSno(form.getUser_id());
        task.setTeam_id(form.getTeam_id());
        task.setStatus(form.getStatus());
        task.setWork_time(form.getWork_time());
        task.setStart_time(form.getStart_time());
        taskDao.insert(task);

        List<String> unsavedFiles = new LinkedList<>();
        form.getAttachments().forEach(attachmentForm -> {
            String dirPath = taskPath + "/" + task.getId();
            String fileName = nameByTime(attachmentForm.getFile());
            File file = new File(new File(dirPath).getAbsolutePath() + "/" + fileName);
            // 检测是否存在目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();// 新建文件夹
            }
            try {
                attachmentForm.getFile().transferTo(file);
            } catch (IOException e) {
                unsavedFiles.add("上传失败文件：" + attachmentForm.getName() + "，错误原因：" + e.getLocalizedMessage());
            }
            Attachment attachment = new Attachment();
            attachment.setName(attachmentForm.getName());
            attachment.setTask_id(task.getId());
            attachment.setPath(task.getId() + "/" + fileName);
            attachmentDao.insert(attachment);
        });
        return unsavedFiles;
    }

    @Override
    public List<Task> getMyTask(Integer user_id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("sno", user_id);
        return taskDao.selectByMap(map);
    }

    @Override
    public List<TaskView> selectTask(Integer id) {
        return taskDao.selectTaskByTeam(id);
    }

    @Override
    public void modifyTask(ModifyTaskForm form) {
        System.out.println(form.getStart_time());
        Task task = new Task();
        task.setId(form.getId());
        task.setName(form.getName());
        task.setIntroduce(form.getIntroduce());
        task.setStage(form.getStage());
        task.setStatus(form.getStatus());
        task.setWork_time(form.getWork_time());
        task.setStart_time(form.getStart_time());
        taskDao.updateById(task);
    }

    @Override
    public void deleteTask(Integer id) {
        taskDao.deleteById(id);
    }

    @Override
    public List<Project> selectProByPro(Integer project_id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("course_id", projectDao.getCourseIdByPro(project_id));
        map.put("deleted", false);
        return projectDao.selectByMap(map);
    }

    @Override
    public void changeProject(ChangeProForm form) {
        Team team = new Team();
        team.setId(form.getTeam_id());
        team.setProject_id(form.getProject_id());
        teamDao.updateById(team);
    }

    @Override
    public TaskDetailView getTaskDetail(Integer task_id) {
        return taskDao.getTaskDetail(task_id);
    }

    //根据案例及时间生成文件名称(时间+三位随机数+文件后缀名)
    private String nameByTime(MultipartFile file) {
        //获取当前时间的时间戳
        long millis = System.currentTimeMillis();

        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;

        return String.valueOf(millis) + str + originalFileName.substring(originalFileName.lastIndexOf("."));
    }
}
